package ltd.jdsoft.cute.token.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ltd.jdsoft.cute.cache.CacheClient;
import ltd.jdsoft.cute.cache.CacheKeyUtil;
import ltd.jdsoft.cute.cache.callback.GetCallback;
import ltd.jdsoft.cute.token.dao.TokenDAO;
import ltd.jdsoft.cute.token.model.Token;

/**
 * 令牌的service层，涉及cache的处理
 * 
 * @author zhengzhq
 *
 */
@Service
public class TokenService {

  @Autowired
  private TokenDAO tokenDAO;
  private CacheKeyUtil cacheKeyUtil = new CacheKeyUtil(Token.class);

  /**
   * 增加令牌
   * 
   * @param token
   */
  public void add(Token token) {
    tokenDAO.add(token);
  }

  /**
   * 获取令牌，优先考虑缓存
   * 
   * @param token
   * @return
   */
  public Token get(String token) {
    return CacheClient.get(cacheKeyUtil.getRecKey("." + token), new GetCallback<Token>() {

      @Override
      public String getCacheGroup() {
        return null;
      }

      @Override
      public Token getObject() {
        return tokenDAO.getByToken(token);
      }
    });
  }

  public Token getByOwnerAndType(long ownerId, int type) {
    return CacheClient.get(cacheKeyUtil.getRecKey(".owner." + ownerId + ".type." + type),
        new GetCallback<Token>() {

          @Override
          public String getCacheGroup() {
            return null;
          }

          @Override
          public Token getObject() {
            return tokenDAO.getByOwnerAndType(ownerId, type);
          }
        });
  }

  /**
   * 更新令牌，需要删除缓存信息
   * 
   * @param token
   */
  public void update(Token token, String oldToken) {
    tokenDAO.update(token);
    CacheClient.remove(cacheKeyUtil.getRecKey("." + oldToken));
    CacheClient.remove(
        cacheKeyUtil.getRecKey(".owner." + token.getOwnerId() + ".type." + token.getType()));
  }
}
